package com.slt.concurrency.mashibing2019.juc.c_000_Thread.my;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class T03_Sleep_Yield_Join {
    public static void main(String[] args) {
//        testSleep();
//        testYield();
        testJoin();
    }


    /**
     * junit 不支持多线程测试
     * @throws InterruptedException
     */
    static void testSleep() {
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    static void testYield() {
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("A " + i);
                if(i % 10 == 0){
                    Thread.yield();
                }
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("------------B " + i);
                if(i % 10 == 0){
                    Thread.yield();
                }
            }
        }).start();
    }

    static void testJoin() {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("A " + i);
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("B " + i);
            }
        });
        thread1.start();
        thread2.start();
    }
}
